package com.abysshal.icarte.datamodel.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.Charset;

import com.abysshal.icarte.datamodel.Config;
import com.abysshal.icarte.datamodel.MyLog;
import com.abysshal.icarte.datamodel.interf.MessageRecvInterf;
import com.abysshal.icarte.datamodel.interf.MessageSendInterf;

public class ClientHandler extends Thread implements MessageSendInterf{
	private Socket socket;
	private MessageRecvInterf mri;
	private BufferedReader br;
	private OutputStream os;
	private boolean running;
	
	public ClientHandler(Socket s, MessageRecvInterf mri){
		this.socket = s;
		this.mri = mri;
		this.running = false;
		this.start();
	}
	
	@Override
	public void run(){
		try {
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			os = socket.getOutputStream();
			running = true;
			while (true) try {
				String read = br.readLine();
				if (read == null) break;
				if (Config.VERBOSE < 2) MyLog.logd("[Client]Read:" + read);
				mri.recv(read, this);				
			} catch (IOException ex){				
			}
		} catch (Exception ex){
			this.running = false;
			return;
		}
		this.running = false;
	}
	
	public boolean running() { return this.running;}

	@Override
	public boolean send(String p) {
		if (Config.VERBOSE < 2) MyLog.logd("[Client]Print:" + p);
		byte[] send = p.getBytes(Charset.forName("UTF-8"));
		int len = send.length;
		try {
			for (int i = 0; i < 32; i += 8) os.write(len >> i);
			os.write(send);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
